﻿using ManageReportVer1.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ViewModels = ManageReportVer1.Models;
namespace ManageReportVer1.Controllers
{
    [Authorize(Roles = "User,Admin")]
    public class AccountController : Controller
    {

        public ActionResult Index()
        {
            DBDataContext DBData = new DBDataContext();
            DashboardModel viewModel = new DashboardModel();
            List<User> tongUser = (from m in DBData.Users
                                       orderby m.UserId ascending
                                       select m).ToList();
            List<Role> tongRole = (from m in DBData.Roles
                                   orderby m.RoleId ascending
                                   select m).ToList();

            //membershipService.GetAllUsers(0, 20, out totalRecords);
            viewModel.TotalUserCount = tongUser.Count();
           // viewModel.TotalUsersOnlineCount = GetNumberOfUsersOnline();
            viewModel.TotalRolesCount = tongRole.Count();

            return View(viewModel);
        }

        //Register
        public ActionResult Register()
        {
            //AccountModel user = new AccountModel();
            //return View(user);

            DBDataContext context = new DBDataContext();
            IEnumerable<Role> Roles = (IEnumerable<Role>)context.Roles;
            List<DropDownListModel> thuVienItems = new List<DropDownListModel>();
            for (int i = 0; i < Roles.Count(); i++)
            {
                thuVienItems.Add(new DropDownListModel { Value = Roles.ElementAt(i).RoleId.ToString(), Name = Roles.ElementAt(i).RoleName.ToString() });
            }
            //RoleModel model = new RoleModel();
            AccountModel user = new AccountModel();
            user.RoleList_Account = new SelectList(thuVienItems, "Value", "Name");

            IEnumerable<Department> Departments= (IEnumerable<Department>)context.Departments;
            List<DropDownListModel> DepartmentItems = new List<DropDownListModel>();
            for (int i = 0; i < Departments.Count(); i++)
            {
                DepartmentItems.Add(new DropDownListModel { Value = Departments.ElementAt(i).DepartmentId.ToString(), Name = Departments.ElementAt(i).DepartmentName.ToString() });
            }
            //RoleModel model = new RoleModel();
            user.DepartmentList_Account = new SelectList(DepartmentItems, "Value", "Name");
            return View(user);
        }

        [HttpPost]
        public ActionResult Register(AccountModel user)
        {

            DBDataContext context = new DBDataContext();
            if (ModelState.IsValid)
            {
                User users = new User();
                users.Password = user.Password;
                users.Email = user.Email;
                users.PasswordQuestion = user.PasswordQuestion;
                users.PasswordAnswer = user.PasswordAnswer;
                users.IsApproved = user.IsApproved;
                //users.IsLockedOut=user.
                users.CreateDate = user.CreateDate = DateTime.Now;
                //users.LastLoginDate=
                //users.LastPasswordChangedDate=
                //users.LastLockoutDate=
                //users.FailedPasswordAttemptCount=
                //users.FailedPasswordAttemptWindowStart=
                //users.FailedPasswordAnswerAttemptCount=
                //users.FailedPasswordAnswerAttemptWindowsStart=
                users.Comment=user.Comment;
                users.DepartmentId = user.departmentId_Account;
                users.FirstName = user.FirstName;
                users.LastName = user.LastName;
                users.UserName = user.UserName;
                users.Honorary = user.Honorary;
                users.Address = user.Address;
                users.Telephone = user.Telephone;
                users.NickName = user.NickName;
                users.DateOfBirth = DateTime.Parse(user.DateOfBirth);
                users.Gender = user.Gender;
                users.MaritalStatus = user.MaritalStatus;
                users.Photo = user.Photo;
                users.RoleId = user.roleId_Account;
                
                context.Users.InsertOnSubmit(users);
                context.SubmitChanges();
                return RedirectToAction("ViewUsers", "Account");
            }
            IEnumerable<Role> Roles = (IEnumerable<Role>)context.Roles;
            List<DropDownListModel> thuVienItems = new List<DropDownListModel>();
            for (int i = 0; i < Roles.Count(); i++)
            {
                thuVienItems.Add(new DropDownListModel { Value = Roles.ElementAt(i).RoleId.ToString(), Name = Roles.ElementAt(i).RoleName.ToString() });
            }
            //RoleModel model = new RoleModel();
            user.RoleList_Account = new SelectList(thuVienItems, "Value", "Name");

            IEnumerable<Department> Departments = (IEnumerable<Department>)context.Departments;
            List<DropDownListModel> DepartmentItems = new List<DropDownListModel>();
            for (int i = 0; i < Departments.Count(); i++)
            {
                DepartmentItems.Add(new DropDownListModel { Value = Departments.ElementAt(i).DepartmentId.ToString(), Name = Departments.ElementAt(i).DepartmentName.ToString() });
            }
            //RoleModel model = new RoleModel();
            user.DepartmentList_Account = new SelectList(DepartmentItems, "Value", "Name");
            return View(user);

        }
        //addRoleToUser
        public ActionResult AddRoleToUser(string username)
        {
            AddRoleToUserModel model = new AddRoleToUserModel();
            model.UserName = username;
            //model.AvailableRoles = (string.IsNullOrEmpty(username) ? new SelectList(roleService.GetAllRoles()) : new SelectList(roleService.AvailableRolesForUser(username)));
            //model.GrantedRoles = (string.IsNullOrEmpty(username) ? new SelectList(new string[] { }) : new SelectList(roleService.GetRolesForUser(username)));

            return View(model);
        }
        //[HttpPost]
        //public ActionResult AddRoleToUser(RoleModel role)
        //{
        //    DBDataContext context = new DBDataContext();
        //    if (ModelState.IsValid)
        //    {
        //        Item items = new Item();
        //        items.ItemName = item.ItemName;
        //        items.DepartmentId = item.DepartmentId;
        //        items.ParentsId = item.itemID;
        //        //    items.ParentsId = item.ItemId;


        //        context.Items.InsertOnSubmit(items);
        //        context.SubmitChanges();
        //        return RedirectToAction("ViewItem", "Item");
        //    }
        //    IEnumerable<Item> Items = (IEnumerable<Item>)context.Items;
        //    List<DropDownListModel> thuVienItems = new List<DropDownListModel>();
        //    for (int i = 0; i < Items.Count(); i++)
        //    {
        //        thuVienItems.Add(new DropDownListModel { Value = Items.ElementAt(i).ItemId.ToString(), Name = Items.ElementAt(i).ItemName.ToString() });
        //    }

        //    item.ItemList = new SelectList(thuVienItems, "Value", "Name");
        //    return View(item);
        //}


        //View User
      //  [Authorize(Roles = "Administrator")]
        public ActionResult ViewUsers()
        {
            ViewBag.Title = "LINQ to SQL";
            DBDataContext context = new DBDataContext();
            var users = from s in context.Users orderby s.UserId ascending select s;
            return View(users.ToList());
        }

        //Update User
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult UpdateUser(string id)
        {
            int userId = Convert.ToInt32(id);
            DBDataContext context = new DBDataContext();
            User user = context.Users.Single(n => n.UserId == userId);         
            return View(user);            
        }
        [HttpPost]
        public ActionResult UpdateUser(User user)
        {
            DBDataContext context = new DBDataContext();
            if (ModelState.IsValid)
            {
                User userupdate = context.Users.Single(s => s.UserId == user.UserId);
                userupdate.Password = user.Password;
                userupdate.Email = user.Email;
                userupdate.PasswordQuestion = user.PasswordQuestion;
                userupdate.PasswordAnswer = user.PasswordAnswer;
                userupdate.IsApproved = user.IsApproved;
                //userupdate.IsLockedOut=user.
                userupdate.CreateDate = user.CreateDate =DateTime.Now;
                //userupdate.LastLoginDate=
                //userupdate.LastPasswordChangedDate=
                //userupdate.LastLockoutDate=
                //userupdate.FailedPasswordAttemptCount=
                //userupdate.FailedPasswordAttemptWindowStart=
                //userupdate.FailedPasswordAnswerAttemptCount=
                //userupdate.FailedPasswordAnswerAttemptWindowsStart=
                userupdate.Comment = user.Comment;
                userupdate.DepartmentId = user.DepartmentId;
                userupdate.FirstName = user.FirstName;
                userupdate.LastName = user.LastName;
                userupdate.UserName = user.UserName;
                userupdate.Honorary = user.Honorary;
                userupdate.Address = user.Address;
                userupdate.Telephone = user.Telephone;
                userupdate.NickName = user.NickName;
                userupdate.DateOfBirth = DateTime.Parse(user.DateOfBirth.ToShortDateString());
                userupdate.Gender = user.Gender;
                userupdate.MaritalStatus = user.MaritalStatus;
                userupdate.Photo = user.Photo;
                userupdate.RoleId = user.RoleId;
                
                context.SubmitChanges();
                return RedirectToAction("ViewUsers", "Account");
            }
            else
                return View(user);
        }

        //Delete user
        public ActionResult DeleteUser(string id)
        {
            int userId = Convert.ToInt32(id);
            DBDataContext context = new DBDataContext();
            User user = context.Users.Single(n => n.UserId == userId);
            context.Users.DeleteOnSubmit(user);
            context.SubmitChanges();
            return RedirectToAction("ViewUsers", "Account");
        }
        [HttpGet]
        public ActionResult CheckForUniqueUser(string userName)
        {
            DBDataContext context = new DBDataContext();
            var user = from s in context.Users where s.UserName.CompareTo(userName)==0 select s.UserName;
          int a;
          if (user.Count() == 0)
              a = 0;
          else
              a = user.Count();
          //  MembershipUser user = membershipService.GetUser(userName);
            JsonResponse response = new JsonResponse();
            response.Exists = (a == 0) ? false : true;

            return Json(response, JsonRequestBehavior.AllowGet);
        }
    }
}
